<template>
  <Container>
    <template v-slot:searchForm>
      <div class="searchRow">
        <el-form class="elForm" ref="form" :model="searchFormData" label-width="80px">
          <el-form-item label="真实姓名">
            <el-input v-model="searchFormData.realName" clearable placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="searchFormData.userName" clearable placeholder="请输入"></el-input>
          </el-form-item>
        </el-form>
        <div class="btnList">
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleClickAddEdit('add')"
            plain>添加</el-button>
          <el-button type="primary" icon="el-icon-search" @click="queryPageList" plain>查 询</el-button>
        </div>
      </div>
    </template>
    <template v-slot:table>
      <el-table :data="tableData" border height="100%" v-loading="loading">
        <el-table-column type="index" width="55" label="序号">
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名">
        </el-table-column>
        <el-table-column prop="userName" label="账号">
        </el-table-column>
        <el-table-column prop="roleTypeStr" label="角色类型">
        </el-table-column>
        <el-table-column prop="phoneNo" label="手机号">
        </el-table-column>
        <el-table-column label="账号状态">
          <template slot-scope="scope">
            <el-switch :disabled="scope.row.userName == 'admin'" v-model="scope.row.accountStatus"
              active-color="#13ce66" inactive-color="#ff4949" @change="editUserStatus({ ...scope.row })" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button v-show="scope.row.roleType == 'ADMINISTRATOR'" type="text"
              @click.stop="handleClickAddEdit('role', scope.row)"
              :disabled="scope.row.userName == 'admin'">分配权限</el-button>
            <el-button v-show="activeName == 'AGENT'" type="text"
              @click.stop="handleClickUserBandDevice(scope.row, 'add')">用户绑定设备</el-button>
            <el-button v-show="activeName == 'AGENT'" type="text"
              @click.stop="handleClickUserBandDevice(scope.row, 'lookView')">查看可用设备</el-button>
            <el-button type="text" :disabled="scope.row.userName == 'admin'"
              @click.stop="handleClickAddEdit('edit', scope.row)">编辑</el-button>
            <el-button type="text" @click.stop="editUserPassword(scope.row)">修改密码</el-button>
            <el-button type="text" :disabled="scope.row.userName == 'admin'"
              @click.stop="handleClickDel([scope.row])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <AddEdit :title="'用户'" roleType="ADMINISTRATOR" @closeDialog="closeDialog" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
      <EditPassword @closeDialog="closeDialog" :dialogVisible="dialogVisibleEditPassword" :data="formData">
      </EditPassword>
      <el-dialog title="分配设备" :visible.sync="dialogVisible_addItem" width="40%" :before-close="handleClose">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="选设备" v-if="deviceFlag == 'add'">
            <el-select class="w100p" v-model="ruleForm.deviceCodeList" clearable filterable multiple collapse-tags
              placeholder="选择选设备">
              <el-option v-for="item, index in deviceList" :key="index" :label="item.deviceCode"
                :value="item.deviceCode"></el-option>
            </el-select>
            <el-button type="text" @click="selectAll">全选</el-button>
            <el-button type="text" @click="clearSelectAll">清除</el-button>
          </el-form-item>
          <el-form-item label="已经选设备" v-if="deviceFlag == 'add'">
            <el-tag size="small" v-if="ruleForm.deviceCodeList && ruleForm.deviceCodeList.length > 0"
              class="el-icon-close" @click="closeItem(item.deviceCode)"
              v-show="ruleForm.deviceCodeList.includes(item.deviceCode)" style="margin-right: 5px; cursor: pointer;"
              v-for="item, index in deviceList" :key="index">{{
                item.deviceCode
              }}</el-tag>
            <span v-show="!ruleForm.deviceCodeList || !ruleForm.deviceCodeList.length">请选择数据项</span>
          </el-form-item>
          <el-form-item label="可用选设备" v-if="deviceFlag == 'lookView'">
            <el-tag size="small" style="margin-right: 5px; cursor: pointer;" v-for="item, index in chooseDeviceCodeList"
              :key="index">{{ item.deviceCode }}</el-tag>
            <span v-show="!chooseDeviceCodeList.length">请选择数据项</span>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_addItem = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </template>
    <template v-slot:pagination>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 100, 200, 300, 400, 500, 600]" :page-size="size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </template>
  </Container>
</template>

<script>
import Container from "@/components/Container"
import AddEdit from './components/addEdit';
import EditPassword from './components/editPassword';
import webUser from "@/api/webUser";
import device from "@/api/device";
export default {
  components: { Container, AddEdit, EditPassword },
  data() {
    return {
      loading: false,
      defaultExpandIds: [],
      tableData: [],
      page: 1,
      size: 100,
      total: 1,
      activeName: 'ADMINISTRATOR',
      selectionList: [],
      funsList: [],
      deviceList: [],
      addEditFlag: 'add',
      deviceFlag: 'add',
      dialogVisible: false,
      dialogVisibleEditPassword: false,
      dialogVisibleFileTable: false,
      dialogVisible_addItem: false,
      formData: {},
      ruleForm: {
        deviceCodeList: []
      },
      chooseDeviceCodeList: [],
      searchFormData: {
        roleType: 'ADMINISTRATOR'
      }
    }
  },
  watch: {},
  mounted() {
    this.queryPageList();
    this.queryDeviceList();
  },
  methods: {
    async handleClickUserBandDevice(row, flag) {
      this.chooseDeviceCodeList = [];
      if (flag == 'lookView') {
        let { data } = await webUser.getListByUserName({ userName: row.userName });
        this.chooseDeviceCodeList = data || [];
      }
      this.ruleForm = { ...row, deviceCodeList: [] };
      this.dialogVisible_addItem = true;
      this.deviceFlag = flag
    },
    async queryDeviceList() {
      let { data } = await device.queryList({});
      this.deviceList = data || []
    },

    closeItem(id) {
      this.ruleForm.deviceCodeList = this.ruleForm.deviceCodeList.filter(e => {
        return e !== id
      })
    },
    clearSelectAll() {
      this.ruleForm.deviceCodeList = []
      this.$set(this.ruleForm, 'deviceCodeList', [])
    },
    selectAll() {
      this.$set(this.ruleForm, 'deviceCodeList', this.deviceList.map(item => {
        return item.deviceCode
      }))
    },
    handleTabClick(el) {
      console.log(el)
      this.page = 1;
      this.searchFormData.roleType = el.paneName
      this.queryPageList()
    },
    async auditUser(data) {
      let { code, msg } = await webUser.examine(data);
      console.log(code, msg)
      if (code == 1) {
        this.$message.success(msg || '操作成功')
      } else {
        this.$message.warning(msg || '操作失败')
      };
      this.queryPageList();
    },
    async submitForm() {
      if (!this.ruleForm.deviceCodeList || !this.ruleForm.deviceCodeList.length) {
        this.$message.warning('请选择数据项')
        return
      };
      let res = await webUser.userBandDeviceList(this.ruleForm);
      if (res.code == 1) {
        this.$message.success(res.msg)
        this.closeDialog();
      } else {
        this.$message.error(res.msg)
      }
    },
    //修改密码
    editUserPassword(data) {
      this.formData = JSON.parse(JSON.stringify(data));
      this.dialogVisibleEditPassword = true;
    },
    //停用/启用用户
    async editUserStatus(data) {
      let { code, msg } = await webUser.editUserStatus(data)
      console.log(code, msg)
      if (code == 1) {
        this.$message.success(msg || '修改成功')
      } else {
        this.$message.warning(msg || '修改失败')
      };
      this.queryPageList()
    },
    queryPageList() {
      this.loading = true;
      webUser.queryPageList({
        page: this.page,
        size: this.size,
        condition: {
          ...this.searchFormData
        }
      }).then(res => {
        this.loading = false;
        let { list, total } = res.data;
        this.tableData = list;
        this.total = total
      }).catch(err => {
        console.log(err)
      })
    },
    closeDialog() {
      this.dialogVisible = false;
      this.dialogVisibleEditPassword = false;
      this.dialogVisibleFileTable = false;
      this.dialogVisible_addItem = false;
      this.formData = {};
      this.queryPageList();
    },
    handleClickDel(rowList = []) {
      let list = [];
      rowList.forEach(item => {
        list.push(item.userId)
      })
      if (rowList.length == 0) return;
      this.$confirm('此操作将永久删除该功能, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        webUser.delList(list).then(res => {
          if (res.code = 1) {
            this.queryPageList();
            this.$message.success('删除成功')
          } else {
            this.$message.warning('删除失败')
          }
        }).catch(err => {
          this.$message.warning('删除失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClickAddEdit(flag = 'add', row = {}) {
      this.formData = JSON.parse(JSON.stringify({
        ...row, roleType: 'ADMINISTRATOR'
      }));
      this.addEditFlag = flag
      this.dialogVisible = true;
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageList();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    }
  }
}
</script>

<style lang="scss" scoped>
.row {
  display: flex;
  justify-content: space-between;
  align-self: flex-start;
}

.elForm {
  width: calc(100% - 200px);
  justify-content: flex-start;
  display: flex;
  flex-wrap: wrap;
}

.btnList {
  width: 200px;
}

.tabsCard {
  height: calc(100% - 60px);
}

::v-deep .el-tabs__content {
  height: calc(100% - 30px) !important;
}

::v-deep .el-tab-pane {
  height: calc(100% - 10px) !important;
}
</style>
